import type { FormProps, FormActions as FormActions, UseFormReturnType, FormSchema } from '../types/form';
import type { NamePath } from 'ant-design-vue/lib/form/interface';
import type { DynamicProps } from '/#/utils';
import { ref, onUnmounted, unref, nextTick, watch } from 'vue';
import { isProdMode } from '/@/utils/env';
import { error } from '/@/utils/log';
import { getDynamicProps } from '/@/utils';

export declare type ValidateFields = (nameList?: NamePath[]) => Promise<Recordable>;

type Props = Partial<DynamicProps<FormProps>>;


/** 向外部提供formApi,UseFormReturnType这个类型没有什么特殊含义,只是使用Form的时候一种返回的type代表可以使用Form的一些函数 */
export function useForm(props?: Props): UseFormReturnType {
    const formRef = ref<Nullable<FormActions>>(null);       // 注意这个的作用
    const loadedRef = ref<Nullable<boolean>>(false);        //是否登陆完毕

    /**  先注册实例,使得getForm/watch可以获取整个实例/props的闭包, 同时可以对props进行动态设置 */
    function register(instance: FormActions) {
        // 是生产环境则卸载的时候清零
        isProdMode() && onUnmounted(() => {
            formRef.value = null;
            loadedRef.value = null;
        });
        // 已经加载成功 且生产环境 且传入的组件是注册组件
        if (unref(loadedRef) && isProdMode() && instance === unref(formRef)) return;

        formRef.value = instance;       //这儿应该是闭包的作用了
        loadedRef.value = true;

        watch(
            () => props,
            () => { props && instance.setProps(getDynamicProps(props)); },
            {
                immediate: true,
                deep: true,     //深度监听每一项prop的变化
            },
        );
    }

    /** 获得form Instance,使用formApi的前提 */
    async function getForm() {
        const form = unref(formRef);
        if (!form) {
            error(
                'The form instance has not been obtained, please make sure that the form has been rendered when performing the form operation!',
            );
        }
        await nextTick();
        return form as FormActions;
    }


    /** 定义Form里面的Actions——formAPI——这个在useFormEvent里面定义 */
    const methods: FormActions = {

        scrollToField: async (name: NamePath, options?: ScrollOptions | undefined) => {
            const form = await getForm();
            form.scrollToField(name, options);
        },

        setProps: async (formProps: Partial<FormProps>) => {
            const form = await getForm();
            form.setProps(formProps);
        },

        updateSchema: async (data: Partial<FormSchema> | Partial<FormSchema>[]) => {
            const form = await getForm();
            form.updateSchema(data);
        },

        resetSchema: async (data: Partial<FormSchema> | Partial<FormSchema>[]) => {
            const form = await getForm();
            form.resetSchema(data);
        },

        clearValidate: async (name?: string | string[]) => {
            const form = await getForm();
            form.clearValidate(name);
        },

        resetFields: async () => {
            getForm().then(async (form) => {
                await form.resetFields();
            });
        },

        removeSchemaByFiled: async (field: string | string[]) => {
            unref(formRef)?.removeSchemaByFiled(field);
        },

        // TODO promisify
        getFieldsValue: <T>() => {
            return unref(formRef)?.getFieldsValue() as T;
        },

        setFieldsValue: async <T>(values: T) => {
            const form = await getForm();
            form.setFieldsValue<T>(values);
        },

        appendSchemaByField: async (
            schema: FormSchema,
            prefixField: string | undefined,
            first: boolean,
        ) => {
            const form = await getForm();
            form.appendSchemaByField(schema, prefixField, first);
        },

        submit: async (): Promise<any> => {
            const form = await getForm();
            return form.submit();
        },

        validate: async (nameList?: NamePath[]): Promise<Recordable> => {
            const form = await getForm();
            return form.validate(nameList);
        },

        validateFields: async (nameList?: NamePath[]): Promise<Recordable> => {
            const form = await getForm();
            return form.validateFields(nameList);
        },
    };

    return [register, methods];
}
